package cn.htu.edu.service.impl;

import cn.htu.edu.common.ResponseHelper;
import cn.htu.edu.common.ResponseModel;
import cn.htu.edu.entity.Orders;
import cn.htu.edu.entity.Users;
import cn.htu.edu.mapper.UsersMapper;
import cn.htu.edu.service.IUsersService;
import cn.htu.edu.utils.StringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dakai
 * @since 2024-05-10
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Resource
    private UsersMapper usersMapper;

    @Override
    public List<Users> getAllUsers() {
        List<Users> users = usersMapper.getAllUsers();
        for (Users user : users) {
            List<Orders> orders = usersMapper.getOrdersByUserId(user.getId());
            user.setOrders(orders);
        }
        return users;
    }

    @Override
    public ResponseModel saveUsers(Users users) {
        //从主表users插入一条记录
        users.setId(StringUtil.createUUID());
        long count = usersMapper.saveUsers(users);
        if(count != 1){
            throw new RuntimeException("插入失败");
        }
        long countUsers = 0;
        //获取主表id
        String userId = users.getId();
        //如果orders表插入数据为空，抛出异常
        if(users.getOrders().size() == 0 || users.getOrders() == null){
            throw new RuntimeException("插入失败");
        }
        //for循环遍历orders表
        for (Orders order: users.getOrders()) {
            order.setId(StringUtil.createUUID());
            //把主表id存到orders表中
            order.setUid(userId);
            //接收order表中的数据
            countUsers = usersMapper.saveOrders(order);
            //判断orders表长度，为空抛出异常
            if(countUsers <= 0){
                throw new RuntimeException("插入失败");
            }
        }
        return ResponseHelper.buildResponseModel("添加成功");
    }

}
